package com.yw.pms.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import com.opensymphony.sitemesh.webapp.SiteMeshFilter;

public class SitemeshFilter extends SiteMeshFilter {
	
	/**
	 * @Fields excludedPages : 需要排除的页面
	 */
	private String excludedPages;
	
	private String[] excludedPageArray;
	
	public void destroy() {
		return;
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		boolean isExcludedPage = false;
		// 判断是否在过滤url之外
		for (String page : excludedPageArray) {
			if (httpRequest.getServletPath().equals(page)) {
				//gethtm
				isExcludedPage = true;
				break;
			}
		}
		//ajax请求不拦截
		if (isExcludedPage || isAjax(httpRequest)) {
			chain.doFilter(request, response);
		} else {
			super.doFilter(request, response, chain);
		}
	}
	
	boolean isAjax(HttpServletRequest request) {
		return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
	}
	
	/**
	 * 初始化函数，获取需要排除在外的url
	 */
	public void init(FilterConfig fConfig) {
		super.init(fConfig);
		excludedPages = fConfig.getInitParameter("excludedPages");
		if (StringUtils.isNotEmpty(excludedPages)) {
			excludedPageArray = excludedPages.split(",");
		}
		return;
	}
}
